package com.zhentao.aop;

import cn.hutool.json.JSONUtil;
import com.zhentao.controller.ChargeUserController;
import com.zhentao.interfaceclass.ChargeUserInterface;
import com.zhentao.model.pojo.user.ChargeUser;
import com.zhentao.model.pojo.user.dto.UserDto;
import com.zhentao.model.pojo.user.log.ChargeUserLog;
import com.zhentao.service.ChargeUserLogService;
import com.zhentao.user.ChargeUserThreadUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Objects;

import static com.zhentao.common.user.UserCommon.CHARGE_USER_LOGIN_KEY_SCHEDULE;

/**
 * @ClassName: ChargeUserLogAop
 * @Author: 振涛教育_Q
 * @Date: 2024/12/31 10:35
 */
@Aspect//声明切面类
@Component
@Slf4j
public class ChargeUserLogAop {
    // @Pointcut("execution(* com.zhentao.controller..*.*(..))")  全部方法

    // 定义一个切入点，匹配 UserService 的所有方法
    @Pointcut("execution(public com.zhentao.model.common.dtos.ResponseResult com.zhentao.controller.ChargeUserController.login(" +
            "com.zhentao.model.pojo.user.dto.UserDto))")
    public void userLogRecord() {
    }

    @Autowired
    private ChargeUserLogService logService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @After("userLogRecord()")
    public void after(JoinPoint joinPoint) {
        log.info("用户操作日志记录");
        // 获取方法签名
        String methodName = joinPoint.getSignature().getName();
        // 获取参数列表
        String argsParam = JSONUtil.toJsonStr(joinPoint.getArgs());
        // 获取方法描述
        Class<ChargeUserController> userClass = ChargeUserController.class;
        String desc = "";
        try {
            Method login = userClass.getMethod("login", UserDto.class);
            ChargeUserInterface annotation = login.getAnnotation(ChargeUserInterface.class);
            if(annotation != null){
                desc+=annotation.value();
            }
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("获取自定义注解描述错误");
        }

        // 获取当前登录的用户id
        Long userId = Long.valueOf(Objects.requireNonNull(redisTemplate.opsForValue().get(CHARGE_USER_LOGIN_KEY_SCHEDULE)));

        // 判断日志表中是否已经存在该用户，那么如果存在的话只增加登录次数就可以
        ChargeUserLog userLog1 = logService.lambdaQuery().eq(ChargeUserLog::getUserId, userId).one();
        if(userLog1 != null){
            userLog1.setCount(userLog1.getCount()+1);
            logService.updateById(userLog1);
            return;
        }

        ChargeUserLog userLog = new ChargeUserLog();
        userLog.setUserId(userId.intValue());
        userLog.setDesc(desc);
        userLog.setParam(argsParam);
        userLog.setSignature(methodName);
        userLog.setCreateTime(LocalDateTime.now());
        logService.save(userLog);

        log.info("用户id：{},操作日志记录成功", userId);
    }

}
